
#数据分类
from  sklearn.datasets import load_iris #Iris植物分类数据集
import numpy as np

dataset = load_iris()
X = dataset.data
Y = dataset.target
#print(dataset.DESCR)

attrbute_means = X.mean(axis=0) #得到一个长度为 0 的numpy 一维数组
print(attrbute_means)
X_d = np.array(X>=attrbute_means,dtype='int') #把数据 X 离散化
#print('X_d=',X_d)

from collections import defaultdict
from operator import itemgetter

#根据待预测数据的某项特征值预测类别，并给出错误率
def train_feature_value(X,y_true,feature_index,value):
    class_counts = defaultdict(int)
    for sample,y in zip(X,y_true):
        if sample[feature_index] == value:
            class_counts[y] += 1
    sorted_class_counts = sorted(class_counts.items(),key=itemgetter(1),reverse=True)
    most_frequent_class = sorted_class_counts[0][0]
    incorrect_predictions = [class_count for class_value, class_count in class_counts.items() 
    if class_value != most_frequent_class]
    error = sum(incorrect_predictions)
    return most_frequent_class, error

def train_on_feature(X,y_true,feature_index):
    values = set(X[:,feature_index])
    predictors = {}
    errors = []
    for current_value in values:
        most_feature_class,error = train_feature_value(X,y_true,feature_index,current_value)
        predictors[current_value] = most_feature_class
        errors.append(error)
    total_error = sum(errors)
    return predictors, total_error

#该模块函数已经弃用
from sklearn.cross_validation import train_test_split #将数据集切分为训练集和测试集的函数
X_train,X_test,y_train,y_test = train_test_split(X_d,Y,random_state=14)

all_predictors = {}
errors = {}
for feature_index in range(X_train.shape[1]):
    predictors, total_error = train_on_feature(X_train, y_train,feature_index)
    all_predictors[feature_index] = predictors
    errors[feature_index] = total_error
best_feature, best_error = sorted(errors.items(), key=itemgetter(1))[0]
print("all_predictors=",all_predictors)
model = {'variable': best_feature,'predictor': all_predictors[best_feature]}
'''
variable = model['variable']
predictor = model['predictor']
prediction = predictor[int(sample[variable])]
'''

def predict(X_test, model):
    variable = model['variable']
    predictor = model['predictor']
    print("variable=",variable,type(variable),"predictor",predictor)
    y_predicted = np.array([predictor[int(sample[variable])] for
    sample in X_test])
    return y_predicted
y_predicted = predict(X_test, model)
accuracy = np.mean(y_predicted == y_test) * 100
print("The test accuracy is {:.1f}%".format(accuracy))

